<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>SpringMVC 解毒3 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SpringMVC 解毒3</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-12T08:38:00+00:00">2018-08-12</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/12/learn-springmvc-code-3/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/12/learn-springmvc-code-3/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/08/12/learn-springmvc-code-3/" class="leancloud_visitors" data-flag-title="SpringMVC 解毒3">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="4-HandlerAdapter"><a href="#4-HandlerAdapter" class="headerlink" title="4 HandlerAdapter"></a>4 HandlerAdapter</h2><img src="http://www.plantuml.com/plantuml/svg/dP914i8W34Ntd88Bo0dSTDouwSQU8DBOTae1GzI5zkvMoy8w5QsicCpFuqs2yA1Rg50wgbJmrDZgGD3XnL6hBhXN0UbiaELLoE4qbf4Ee55kmPO6AIl13oNH2_4ZITLZPoHg0o78ekcymM9ClA4VgMb9hc-hLR9dWKvtrgf3hbqPZM0Vc42ppE8bilDdw9jLikalBGNMEWPkd9tCR8V74mREmVk1CZEqbCeecqGiavseRPbzPCzulQvyuooJCqFYnwsdqP__oSU7-Zi0">

<a id="more"></a>

<p>第三章将 HandlerMapping的时候，我们看到抽象类 AbstractUrlHandlerMapping 中的映射的handler都是Object类型的，而抽象类 AbstractHandlerMethodMapping 的最终实现类的handler必须是方法，类必须有<code>@Controller</code>或<code>@RequestMapping</code>注解，对应的方法也得有<code>@RequestMapping</code>注解。</p>
<p>所以说 AbstractHandlerMethodMapping 的最终实现类生成的handler应该有特定的 HandlerAdapter 实现类去运行，而 AbstractUrlHandlerMapping 的最终实现类生成的handler，如果没有使用标准的接口或抽象类，那么就没有对应的 HandlerAdapter，原因是SpringMVC并不知道你的类应该运行哪个方法，怎么设置参数等等。</p>
<p>接下来让我们来认识认识 HandlerAdapter 吧。</p>
<h3 id="4-1-HandlerAdapter-接口"><a href="#4-1-HandlerAdapter-接口" class="headerlink" title="4.1 HandlerAdapter 接口"></a>4.1 HandlerAdapter 接口</h3><img src="http://www.plantuml.com/plantuml/svg/VOv12i9034NtFKMM5Nk9BeGk5471_RJpsuuCat6IMa6ykmFjnYxC9Y7lm_k52uhKcmxKc60zKcrDp2zw5vHdJospXmaaKuoSLCfpUqUdD2xntHexiOMlWxqvp2ih6zLuHNfww0MF2QAKbbtH3vF8GP3XSbIqSP2EYMUXmwj3LCTXbNeE0mtGen7D1LplOFzQjzq_nHS0">

<p>HandlerAdapter 接口实际上有三个方法，我们比较关注的是其中两个。</p>
<p>第一个是supports方法，在2.4.2节中，我们看到在<code>DispatcherServlet</code>中doDispatch方法执行时，如果拿到了持有handler的执行链，会循环调用每一个 HandlerAdapter 的supports方法判断当前的 HandlerAdapter 实现类是否支持这个handler，如果支持，就返回该 HandlerAdapter 实现类。最后，如果都没有支持的，就会抛出异常。</p>
<p>第二个是handle方法，还是在2.4.2节，通过第一个方法得到了handler对应的adpater之后，会先调用执行链的前处理方法，在3.1节中有讲到是如何调用的。调用完前处理方法后，会用找到的adapter调用handle方法返回 ModelAndView。</p>
<p>以下的几个小节都会围绕这个两个方法展开。</p>
<p>还有，为了对应 HandlerMapping 中的顺序，HandlerAdapter 子类也是有顺序的。</p>
<h3 id="4-2-SimpleServletHandlerAdapter-分析"><a href="#4-2-SimpleServletHandlerAdapter-分析" class="headerlink" title="4.2 SimpleServletHandlerAdapter 分析"></a>4.2 SimpleServletHandlerAdapter 分析</h3><p>说实话 SimpleServletHandlerAdapter 实在没什么分析的。但是！！！，你一定要理解我在 HandlerMapping 分析中讲的，handler除了在 AbstractHandlerMethodMapping 是被SpringMVC规范的，其他handler都是object，具体怎么用全靠adapter说了算。</p>
<p>好了，直接看源码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleServletHandlerAdapter</span> <span class="keyword">implements</span> <span class="title">HandlerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Object handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (handler <span class="keyword">instanceof</span> Servlet);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ModelAndView <span class="title">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        ((Servlet) handler).service(request, response);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getLastModified</span><span class="params">(HttpServletRequest request, Object handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>惊不惊喜？意不意外？就这么简单，如果你给 AbstractUrlHandlerMapping 最终实现类中设置的bean是实现Servlet接口的或者间接实现Servlet接口的，那么他会直接调用Servlet接口的service方法。</p>
<h3 id="4-3-HttpRequestHandlerAdapter-分析"><a href="#4-3-HttpRequestHandlerAdapter-分析" class="headerlink" title="4.3 HttpRequestHandlerAdapter 分析"></a>4.3 HttpRequestHandlerAdapter 分析</h3><p>哇，这个类了不起啊，这个类几乎和4.2节 SimpleServletHandlerAdapter 一模一样。它对应的接口是 HttpRequestHandler，这个接口也了不起，除了没有init和destroy方法，其他和Servlet接口差不多。HttpRequestHandler 接口是SpringMVC自定义的一个接口，入参是request和response，具体这个接口怎么使用，后面的章节会讲到，但是我在这里告诉你关于静态资源文件的映射的handler就是实现这个接口的。</p>
<p>类代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HttpRequestHandlerAdapter</span> <span class="keyword">implements</span> <span class="title">HandlerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Object handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (handler <span class="keyword">instanceof</span> HttpRequestHandler);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ModelAndView <span class="title">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        ((HttpRequestHandler) handler).handleRequest(request, response);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getLastModified</span><span class="params">(HttpServletRequest request, Object handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> LastModified) &#123;</span><br><span class="line">            <span class="keyword">return</span> ((LastModified) handler).getLastModified(request);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1L</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-4-SimpleControllerHandlerAdapter-分析"><a href="#4-4-SimpleControllerHandlerAdapter-分析" class="headerlink" title="4.4 SimpleControllerHandlerAdapter 分析"></a>4.4 SimpleControllerHandlerAdapter 分析</h3><p>经过前两个类分析，可以总结出一个规律，那就是使用 AbstractUrlHandlerMapping 基于类的URI映射都是比较简单的。那么这个类也一样，但是需要额外提一下的是 HttpRequestHandlerAdapter 跟我们的业务逻辑handler关系不大，但你写业务逻辑的handler可能就会用到 SimpleControllerHandlerAdapter。因为这个类对应的handler，其实现的接口是<code>Controller</code>，注意是接口不是注解，在最开始学些SpringMVC开发时，你可能接触过。</p>
<p>以下是类代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleControllerHandlerAdapter</span> <span class="keyword">implements</span> <span class="title">HandlerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Object handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (handler <span class="keyword">instanceof</span> Controller);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ModelAndView <span class="title">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> ((Controller) handler).handleRequest(request, response);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getLastModified</span><span class="params">(HttpServletRequest request, Object handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> LastModified) &#123;</span><br><span class="line">            <span class="keyword">return</span> ((LastModified) handler).getLastModified(request);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1L</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-5-AbstractHandlerMethodAdapter-分析"><a href="#4-5-AbstractHandlerMethodAdapter-分析" class="headerlink" title="4.5 AbstractHandlerMethodAdapter 分析"></a>4.5 AbstractHandlerMethodAdapter 分析</h3><p>前边三个adapter实现类都很容易理解，但是接下来的实现类都是基于方法映射的了，有点难度，大家打起精神来，攻克adapter最后的难关。</p>
<p>AbstractHandlerMethodAdapter 抽象类相比 AbstractHandlerMethodMapping 抽象类要简单的多，原因是mapping需要指导映射规则生成和匹配，而adapter这边只需要支持方法执行。</p>
<p>实际上 AbstractHandlerMethodAdapter 只增加了可排序接口，并且指定了handler最起码需要是HandlerMethod，这里简单看看源码就行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * This implementation expects the handler to be an &#123;<span class="doctag">@link</span> HandlerMethod&#125;.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handler the handler instance to check</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> whether or not this adapter can adapt the given handler</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Object handler)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (handler <span class="keyword">instanceof</span> HandlerMethod &amp;&amp; supportsInternal((HandlerMethod) handler));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Given a handler method, return whether or not this adapter can support it.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handlerMethod the handler method to check</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> whether or not this adapter can adapt the given method</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">boolean</span> <span class="title">supportsInternal</span><span class="params">(HandlerMethod handlerMethod)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * This implementation expects the handler to be an &#123;<span class="doctag">@link</span> HandlerMethod&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> ModelAndView <span class="title">handle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> handleInternal(request, response, (HandlerMethod) handler);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Use the given handler method to handle the request.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handlerMethod handler method to use. This object must have previously been passed to the</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> #supportsInternal(HandlerMethod)&#125; this interface, which must have returned &#123;<span class="doctag">@code</span> true&#125;.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> ModelAndView object with the name of the view and the required model data,</span></span><br><span class="line"><span class="comment"> * or &#123;<span class="doctag">@code</span> null&#125; if the request has been handled directly</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception in case of errors</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> ModelAndView <span class="title">handleInternal</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletResponse response, HandlerMethod handlerMethod)</span> <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<h3 id="4-6-RequestMappingHandlerAdapter-分析"><a href="#4-6-RequestMappingHandlerAdapter-分析" class="headerlink" title="4.6 RequestMappingHandlerAdapter 分析"></a>4.6 RequestMappingHandlerAdapter 分析</h3><img src="http://www.plantuml.com/plantuml/svg/fLB1Rjim3BtdA_G3-uCYWzEks82vAPAYEmmxo1BhS9D9JwBQPSF-VRGX8qtYz39VR3-HJ-_nSU62JSbiu6U69BNjUwJseoKV85RUzWBH_5aiZ3xlp6TCSbKEQv0T-ogskGEI3IGEpn2NnkKat9tYgJ2ysNpDNSy91OpzltOab1MILmiNYCwTR41of4SRCXHyyd9-CYldlEmWA5wa68NKx25Kv1yHNWwJx6RGgUsQITJM7RGiQ0MPQaksrR3SfPCZvo9z3IafhapAgp5VlL_gdIVWaSnrynsSBDNDk2oggMTAi6A_h_mpEYZ5Nw0Pfg-Bz4c3G1lmjmfxcKDBHvNsv1vi-l7X5xWi78sy-faqCBN63fLbMn-m0yuoZSI6O9i0zv6TkXZlKGSEUgNu-isuSluAdTpTm1F421fXoa4k4VYZgXcQXZc09OCjSGGbjLetPhkc3NYCEhrIYYGgoErW2ngOJxSSjyETJ9L8n2RBwQ9Cv8F_NMJIwQsfz9IIKuQjQWEJvj3ISM-ZxK2DtEdh1fDZZLspwkVnm_8zOPlZCCsLQhgrJZdtfZbyZvMBluj_">

<p>到这了务必打起精神，因为这块的难度可能要比<code>DispatcherServlet</code>还要难，这里是SpringMVC除了<code>DispatcherServlet</code>外最精髓的地方，可以和bean创建的代码一较高低。由于在这个类中引入了比较多的接口和类，所以我先带大家简单梳理一下用到的接口和类。这些接口和类后面的章节也会讲到，这里只不过是提前熟悉一下。</p>
<h4 id="4-6-1-HandlerMethodArgumentResolver-分析"><a href="#4-6-1-HandlerMethodArgumentResolver-分析" class="headerlink" title="4.6.1 HandlerMethodArgumentResolver 分析"></a>4.6.1 HandlerMethodArgumentResolver 分析</h4><img src="http://www.plantuml.com/plantuml/svg/TOxDJiD038JlUGeV6v6NQ0iLb_ueXt9siWDTbDYfrqb0Y7Sd8ct41PzcB7yppg8ux9Lhq3DBQ61x-4N3sjxw5k8baZO3ZBwoZAPve4gr0GkblklKF9tOkCKKifh9nLDtL_aDFLRlg9riphnN_CyLjDU0PYtX735kLPoZJ0Sj3uif3knnm0kg4jSUoMbSP47J-f6TDr42RCUrgtrIzTVbv1VJCT7JHutEeqhs_Vlk3m00">

<p>这个接口是用来解析方法入参的，能够将从request和配置中的信息解析为方法入参。而 HandlerMethodArgumentResolverComposite 则是该接口的一个实现类，它的作用是代理所有的接口实现类。向 HandlerMethodArgumentResolverComposite 添加一组方法入参解析器，而后只调用 HandlerMethodArgumentResolverComposite 的相关接口方法，HandlerMethodArgumentResolverComposite 会自动匹配它包含的所有解析器中最合适的，并代理执行。</p>
<h4 id="4-6-2-HandlerMethodReturnValueHandler-分析"><a href="#4-6-2-HandlerMethodReturnValueHandler-分析" class="headerlink" title="4.6.2 HandlerMethodReturnValueHandler 分析"></a>4.6.2 HandlerMethodReturnValueHandler 分析</h4><img src="http://www.plantuml.com/plantuml/svg/TOt13e9034JlV4MF4la9OqoyeCOOF1Ts36jWYqi1ZV7VHK3YnJcrqvbNwnJ-mXbeoyuKy34q5tE4DjubN3IOV7e60VLQKYfIW1tLJLM9rthCdXuL5cFvm9vBz5poyodyT2T0AzPGFc1__YpswHMPJft1YkW_C1fWNyLYKAoSIIowjJXbw_fqoUsyHBHZjItEI8-uDQYLkdaCINClNKsRUuPAhRZWzGO0">

<p>HandlerMethodReturnValueHandler 接口用来处理方法的返回参数。HandlerMethodReturnValueHandlerComposite 则是该接口的一个实现类，它的作用是代理一组 HandlerMethodReturnValueHandler 接口实现类，挑选最合适的实现类执行。</p>
<h4 id="4-6-3-HttpMessageConverter-分析"><a href="#4-6-3-HttpMessageConverter-分析" class="headerlink" title="4.6.3 HttpMessageConverter 分析"></a>4.6.3 HttpMessageConverter 分析</h4><img src="http://www.plantuml.com/plantuml/svg/bP3BYW8n44NtViLTAle9uYn4665KS1fSbqcD4sXJ8QdsYVzkjuycucOcgwhKwzphl7By8SFuL0qpJeasF1Q_urWNSEvqKBy-rY8bauSXlsIotN59AGq_HZ0bdKu3pDWwAew1iNr6lVVHLNJA_vdzSac7RNs43Ujt5OBKSBRzJjrdUu6OmO4Fojuc5EsfHkJKXqeVIk6of0VzZR9Fc2uc1yD1dVX1xijSj15FwvBRXiVbdJYB_KrU0Sqr6Qajzjh4zsMBIZC0oRE_43GUlX9SRWnN">

<p>HttpMessageConverter 是用来解析request中的数据和向response中写入数据的。</p>
<h4 id="4-6-4-ParameterNameDiscoverer-分析"><a href="#4-6-4-ParameterNameDiscoverer-分析" class="headerlink" title="4.6.4 ParameterNameDiscoverer 分析"></a>4.6.4 ParameterNameDiscoverer 分析</h4><img src="http://www.plantuml.com/plantuml/svg/uyhCAqajIajCJbK8I2nAp4q5ylo0b4jcSN9-MMfHQf52DHUN0X1eAmIN56NcfKV7AgIdbg0eBjRmJIt9o4zHo0LJceJLE-Vd5PSKbIQNv1VPsDifW6XDhbek0000">

<p>ParameterNameDiscoverer 接口是从方法和构造函数中获取参数名的。别以为参数名好搞，你在IDE中写的方法入参名假设是methodParameter1，等编译完毕，你再用IDE的反编译功能反编译一下，会发现方法入参名变成var1/var2之类的了。</p>
<p>所以，Spring采用的办法是使用ASM字节码操作框架直接从本地变量表中获取方法入参名，相关的类是<code>LocalVariableTableParameterNameDiscoverer</code>。</p>
<p>而从JDK1.8起，JDK中自带了<code>java.lang.reflect.Parameter</code>类，可以直接从这里获取方法入参名，所以Spring会先判断JVM使用的版本环境，如果包含<code>java.lang.reflect.Executable</code>类，说明是JDK1.8，就默认使用<code>StandardReflectionParameterNameDiscoverer</code>类获取变量，而不是用ASM字节码操作框架。</p>
<h4 id="4-6-5-ModelAndViewContainer-分析"><a href="#4-6-5-ModelAndViewContainer-分析" class="headerlink" title="4.6.5 ModelAndViewContainer 分析"></a>4.6.5 ModelAndViewContainer 分析</h4><img src="http://www.plantuml.com/plantuml/svg/NKyxJyCm4DxpAsui0njR0IdG8KjLYKZib_XI3fbpy5t8WFZlk7crYHVBdxzdxL4LZi6HpyMzC_MlGGnPAC9lba4wzr25u0a5-2mXqe4QxBmDcfEyaUD8jS4JDEYLzfFcL7rUq9_aE4CD2_enwuWjk1kVf1RguON5iPpp7YFDlDtTh5-KSSeSWFscvEgph4amSjYs6wkKP8-bnPJu3DKOVM35ofFBBU5LPwHJjGBruuQ_UrXg5MPjQMYTWWxNDaILWyoCrMkqBlchzRJYNKTVPtrtf5QWk5HlsNCXPN__">

<p>ModelAndViewContainer 是 ModelAndView 产生之前的包装器，例如方法返回了model，则需要判断是否自动添加view，如果返回了view，需要生成一个model出来等等。    </p>
<h4 id="4-6-6-ServletInvocableHandlerMethod-和-InvocableHandlerMethod-分析"><a href="#4-6-6-ServletInvocableHandlerMethod-和-InvocableHandlerMethod-分析" class="headerlink" title="4.6.6 ServletInvocableHandlerMethod 和 InvocableHandlerMethod 分析"></a>4.6.6 ServletInvocableHandlerMethod 和 InvocableHandlerMethod 分析</h4><img src="http://www.plantuml.com/plantuml/svg/bL11RW8n3Bpd5Vd0vWLSgd8e1wgAIjnDCCkA98vixtAW-_Tk5n2aG4LzI2JFU3oU37u7DLhYsadc9jKRXeXxuftRuyf5r2sjxS4OEvGF86BV8Aq3ydo4J6_oKnfEsfo9jTIQfOuyh08MeWF7dgegrxrmtKPCka2Xq26_KimaZQA5NuXSINp0Zo55VX--QIEU1WAopVVxusG_lgMjoLTLFR3yH0w2t0LK5pj_pWHI8WLjA9MnV1wf_qrdWTfoMa9epnENVFW6awix7smQ3_xJZEc_0G00">


<p>还记得3.8.1节讲到的 HandlerMethod 吗？HandlerMethod 只是一些数据的组合，而 ServletInvocableHandlerMethod 和 InvocableHandlerMethod 则给 HandlerMethod 装上了方法，使 HandlerMethod 中的method、bean等数据可以被调用。</p>
<h4 id="4-6-7-RequestMappingHandlerAdapter-初始化分析"><a href="#4-6-7-RequestMappingHandlerAdapter-初始化分析" class="headerlink" title="4.6.7 RequestMappingHandlerAdapter 初始化分析"></a>4.6.7 RequestMappingHandlerAdapter 初始化分析</h4><p>由于要处理request解析入参、方法反射调用、返回结果处理等等事情，所以这个类初始化的东西也很多。我们来找一找初始化点吧。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">RequestMappingHandlerAdapter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    StringHttpMessageConverter stringHttpMessageConverter = <span class="keyword">new</span> StringHttpMessageConverter();</span><br><span class="line">    stringHttpMessageConverter.setWriteAcceptCharset(<span class="keyword">false</span>);  <span class="comment">// see SPR-7316</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">this</span>.messageConverters = <span class="keyword">new</span> ArrayList&lt;HttpMessageConverter&lt;?&gt;&gt;(<span class="number">4</span>);</span><br><span class="line">    <span class="keyword">this</span>.messageConverters.add(<span class="keyword">new</span> ByteArrayHttpMessageConverter());</span><br><span class="line">    <span class="keyword">this</span>.messageConverters.add(stringHttpMessageConverter);</span><br><span class="line">    <span class="keyword">this</span>.messageConverters.add(<span class="keyword">new</span> SourceHttpMessageConverter&lt;Source&gt;());</span><br><span class="line">    <span class="keyword">this</span>.messageConverters.add(<span class="keyword">new</span> AllEncompassingFormHttpMessageConverter());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>首先第一个就是构造函数，在构造函数中，初始化了消息转换器。</p>
<ul>
<li><code>StringHttpMessageConverter</code>的作用是把body部分的字节数组转化为String，将String类型的数据写入到response的outputStream中。</li>
<li><code>ByteArrayHttpMessageConverter</code>的作用是把body部分的字节数组转到新的字节数组中，将字节数组写入到response的outputStream中。</li>
<li><code>SourceHttpMessageConverter</code>的作用是body部分的字节数组转化为xml对象，将xml对象写入到response的outputStream中。</li>
<li><code>AllEncompassingFormHttpMessageConverter</code>的作用是将body中xml或json部分数据转化为对象，将多个xml对象或多个json对象写入到response的outputStream中。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Do this first, it may add ResponseBody advice beans</span></span><br><span class="line">    initControllerAdviceCache();</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.argumentResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        List&lt;HandlerMethodArgumentResolver&gt; resolvers = getDefaultArgumentResolvers();</span><br><span class="line">        <span class="keyword">this</span>.argumentResolvers = <span class="keyword">new</span> HandlerMethodArgumentResolverComposite().addResolvers(resolvers);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.initBinderArgumentResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        List&lt;HandlerMethodArgumentResolver&gt; resolvers = getDefaultInitBinderArgumentResolvers();</span><br><span class="line">        <span class="keyword">this</span>.initBinderArgumentResolvers = <span class="keyword">new</span> HandlerMethodArgumentResolverComposite().addResolvers(resolvers);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.returnValueHandlers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        List&lt;HandlerMethodReturnValueHandler&gt; handlers = getDefaultReturnValueHandlers();</span><br><span class="line">        <span class="keyword">this</span>.returnValueHandlers = <span class="keyword">new</span> HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the list of argument resolvers to use including built-in resolvers</span></span><br><span class="line"><span class="comment"> * and custom resolvers provided via &#123;<span class="doctag">@link</span> #setCustomArgumentResolvers&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;HandlerMethodArgumentResolver&gt; <span class="title">getDefaultArgumentResolvers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;HandlerMethodArgumentResolver&gt; resolvers = <span class="keyword">new</span> ArrayList&lt;HandlerMethodArgumentResolver&gt;();</span><br><span class="line">    <span class="comment">// Annotation-based argument resolution</span></span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMethodArgumentResolver(getBeanFactory(), <span class="keyword">false</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> PathVariableMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> PathVariableMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MatrixVariableMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MatrixVariableMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletModelAttributeMethodProcessor(<span class="keyword">false</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestResponseBodyMethodProcessor(getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestPartMethodArgumentResolver(getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestHeaderMethodArgumentResolver(getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestHeaderMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletCookieValueMethodArgumentResolver(getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ExpressionValueMethodArgumentResolver(getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> SessionAttributeMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestAttributeMethodArgumentResolver());</span><br><span class="line">    <span class="comment">// Type-based argument resolution</span></span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletRequestMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletResponseMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> HttpEntityMethodProcessor(getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RedirectAttributesMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ModelMethodProcessor());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MapMethodProcessor());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ErrorsMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> SessionStatusMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> UriComponentsBuilderMethodArgumentResolver());</span><br><span class="line">    <span class="comment">// Custom arguments</span></span><br><span class="line">    <span class="keyword">if</span> (getCustomArgumentResolvers() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        resolvers.addAll(getCustomArgumentResolvers());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Catch-all</span></span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMethodArgumentResolver(getBeanFactory(), <span class="keyword">true</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletModelAttributeMethodProcessor(<span class="keyword">true</span>));</span><br><span class="line">    <span class="keyword">return</span> resolvers;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the list of return value handlers to use including built-in and</span></span><br><span class="line"><span class="comment"> * custom handlers provided via &#123;<span class="doctag">@link</span> #setReturnValueHandlers&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;HandlerMethodReturnValueHandler&gt; <span class="title">getDefaultReturnValueHandlers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;HandlerMethodReturnValueHandler&gt; handlers = <span class="keyword">new</span> ArrayList&lt;HandlerMethodReturnValueHandler&gt;();</span><br><span class="line">    <span class="comment">// Single-purpose return value types</span></span><br><span class="line">    handlers.add(<span class="keyword">new</span> ModelAndViewMethodReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> ModelMethodProcessor());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> ViewMethodReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> ResponseBodyEmitterReturnValueHandler(getMessageConverters()));</span><br><span class="line">    handlers.add(<span class="keyword">new</span> StreamingResponseBodyReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> HttpEntityMethodProcessor(getMessageConverters(),</span><br><span class="line">            <span class="keyword">this</span>.contentNegotiationManager, <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    handlers.add(<span class="keyword">new</span> HttpHeadersReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> CallableMethodReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> DeferredResultMethodReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> AsyncTaskMethodReturnValueHandler(<span class="keyword">this</span>.beanFactory));</span><br><span class="line">    <span class="comment">// Annotation-based return value types</span></span><br><span class="line">    handlers.add(<span class="keyword">new</span> ModelAttributeMethodProcessor(<span class="keyword">false</span>));</span><br><span class="line">    handlers.add(<span class="keyword">new</span> RequestResponseBodyMethodProcessor(getMessageConverters(),</span><br><span class="line">            <span class="keyword">this</span>.contentNegotiationManager, <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    <span class="comment">// Multi-purpose return value types</span></span><br><span class="line">    handlers.add(<span class="keyword">new</span> ViewNameMethodReturnValueHandler());</span><br><span class="line">    handlers.add(<span class="keyword">new</span> MapMethodProcessor());</span><br><span class="line">    <span class="comment">// Custom return value types</span></span><br><span class="line">    <span class="keyword">if</span> (getCustomReturnValueHandlers() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers.addAll(getCustomReturnValueHandlers());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Catch-all</span></span><br><span class="line">    <span class="keyword">if</span> (!CollectionUtils.isEmpty(getModelAndViewResolvers())) &#123;</span><br><span class="line">        handlers.add(<span class="keyword">new</span> ModelAndViewResolverMethodReturnValueHandler(getModelAndViewResolvers()));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        handlers.add(<span class="keyword">new</span> ModelAttributeMethodProcessor(<span class="keyword">true</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> handlers;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>第二个初始化点在 afterPropertiesSet 方法。在这个方法中，我们重点关注两个内容，一个是方法入参解析器加载，另一个是返回参数处理器加载。</p>
<p>在方法入参解析器加载中，把解析器分为四种类型，第一种是基于注解的解析器，第二种是基于类型的解析器，第三种是通用解析器，最后一种是默认解析器。</p>
<p>在返回结果处理器加载中，把处理器分为五种类型，第一种是单目的类型处理器，第二种是使用注解类型处理器，第三种是多目的类型处理器，第四种是通用类型处理器，最后一种是默认处理器。</p>
<p>在生成这些解析器处理器时，有的构造方法引入了web应用上下文，有的引入了属性messageConverters。能说明什么问题呢？说明这些解析器处理器需要从web应用上下文中获取bean供它们使用，需要使用messageConverter对入参或者返回结果进行转换。至于这些解析器处理器分别都是干什么的，目前先不展开，否则你会迷失在 RequestMappingHandlerAdapter。</p>
<h4 id="4-6-8-RequestMappingHandlerAdapter-处理请求分析"><a href="#4-6-8-RequestMappingHandlerAdapter-处理请求分析" class="headerlink" title="4.6.8 RequestMappingHandlerAdapter 处理请求分析"></a>4.6.8 RequestMappingHandlerAdapter 处理请求分析</h4><p>前面提到 AbstractHandlerMethodAdapter 抽象类只确定了handler必须是HandlerMethd类型，其余的都留给子类实现。</p>
<p>RequestMappingHandlerAdapter 中，针对判断是不是handler直接返回了true，说明handler只要是HandlerMethd类型的，都可以处理。</p>
<p>下面是重写的handleInternal方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> ModelAndView <span class="title">handleInternal</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletResponse response, HandlerMethod handlerMethod)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ModelAndView mav;</span><br><span class="line">    checkRequest(request);</span><br><span class="line">    <span class="comment">// Execute invokeHandlerMethod in synchronized block if required.</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.synchronizeOnSession) &#123;</span><br><span class="line">        HttpSession session = request.getSession(<span class="keyword">false</span>);</span><br><span class="line">        <span class="keyword">if</span> (session != <span class="keyword">null</span>) &#123;</span><br><span class="line">            Object mutex = WebUtils.getSessionMutex(session);</span><br><span class="line">            <span class="keyword">synchronized</span> (mutex) &#123;</span><br><span class="line">                mav = invokeHandlerMethod(request, response, handlerMethod);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// No HttpSession available -&gt; no mutex necessary</span></span><br><span class="line">            mav = invokeHandlerMethod(request, response, handlerMethod);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// No synchronization on session demanded at all...</span></span><br><span class="line">        mav = invokeHandlerMethod(request, response, handlerMethod);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!response.containsHeader(HEADER_CACHE_CONTROL)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) &#123;</span><br><span class="line">            applyCacheSeconds(response, <span class="keyword">this</span>.cacheSecondsForSessionAttributeHandlers);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            prepareResponse(response);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> mav;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>我们看到重写的handleInternal又调用了invokeHandlerMethod方法，看来这个方法才是重点。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Invoke the &#123;<span class="doctag">@link</span> RequestMapping&#125; handler method preparing a &#123;<span class="doctag">@link</span> ModelAndView&#125;</span></span><br><span class="line"><span class="comment"> * if view resolution is required.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 4.2</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #createInvocableHandlerMethod(HandlerMethod)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> ModelAndView <span class="title">invokeHandlerMethod</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletResponse response, HandlerMethod handlerMethod)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ServletWebRequest webRequest = <span class="keyword">new</span> ServletWebRequest(request, response);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);</span><br><span class="line">        ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);</span><br><span class="line">        ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);</span><br><span class="line">        invocableMethod.setHandlerMethodArgumentResolvers(<span class="keyword">this</span>.argumentResolvers);</span><br><span class="line">        invocableMethod.setHandlerMethodReturnValueHandlers(<span class="keyword">this</span>.returnValueHandlers);</span><br><span class="line">        invocableMethod.setDataBinderFactory(binderFactory);</span><br><span class="line">        invocableMethod.setParameterNameDiscoverer(<span class="keyword">this</span>.parameterNameDiscoverer);</span><br><span class="line">        ModelAndViewContainer mavContainer = <span class="keyword">new</span> ModelAndViewContainer();</span><br><span class="line">        mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));</span><br><span class="line">        modelFactory.initModel(webRequest, mavContainer, invocableMethod);</span><br><span class="line">        mavContainer.setIgnoreDefaultModelOnRedirect(<span class="keyword">this</span>.ignoreDefaultModelOnRedirect);</span><br><span class="line">        AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);</span><br><span class="line">        asyncWebRequest.setTimeout(<span class="keyword">this</span>.asyncRequestTimeout);</span><br><span class="line">        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);</span><br><span class="line">        asyncManager.setTaskExecutor(<span class="keyword">this</span>.taskExecutor);</span><br><span class="line">        asyncManager.setAsyncWebRequest(asyncWebRequest);</span><br><span class="line">        asyncManager.registerCallableInterceptors(<span class="keyword">this</span>.callableInterceptors);</span><br><span class="line">        asyncManager.registerDeferredResultInterceptors(<span class="keyword">this</span>.deferredResultInterceptors);</span><br><span class="line">        <span class="keyword">if</span> (asyncManager.hasConcurrentResult()) &#123;</span><br><span class="line">            Object result = asyncManager.getConcurrentResult();</span><br><span class="line">            mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[<span class="number">0</span>];</span><br><span class="line">            asyncManager.clearConcurrentResult();</span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Found concurrent result value ["</span> + result + <span class="string">"]"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            invocableMethod = invocableMethod.wrapConcurrentResult(result);</span><br><span class="line">        &#125;</span><br><span class="line">        invocableMethod.invokeAndHandle(webRequest, mavContainer);</span><br><span class="line">        <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> getModelAndView(mavContainer, modelFactory, webRequest);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        webRequest.requestCompleted();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码从第11行到第28行都是在做准备工作，除开异步响应相关代码，主要内容有初始化 ServletInvocableHandlerMethod 对象，初始化 ModelAndViewContainer 对象。可以看到，在 RequestMappingHandlerAdapter 初始化的属性：方法入参解析器代理类，返回结果处理器代理类、方法入参名探索器等等。</p>
<p>在第38行则调用了 ServletInvocableHandlerMethod 对象的invokeAndHandle方法，这个方法应该干的就是：方法入参解析、反射方法调用、返回结果处理等。</p>
<p>在第42行，则是调用getModelAndView方法生成ModelAndView，假如方法返回null、方法中已经向response写入数据、返回结果处理器向response写入数据，都返回null，也就是不需要 ViewResolver 进行渲染。</p>
<p>既然大致步骤我们都知道了，接下来就是休闲时刻，来看看反射方法调用吧。</p>
<p><code>ServletInvocableHandlerMethod.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Invokes the method and handles the return value through one of the</span></span><br><span class="line"><span class="comment"> * configured &#123;<span class="doctag">@link</span> HandlerMethodReturnValueHandler&#125;s.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> webRequest the current request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> mavContainer the ModelAndViewContainer for this request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> providedArgs "given" arguments matched by type (not resolved)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invokeAndHandle</span><span class="params">(ServletWebRequest webRequest,</span></span></span><br><span class="line"><span class="function"><span class="params">        ModelAndViewContainer mavContainer, Object... providedArgs)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);</span><br><span class="line">    setResponseStatus(webRequest);</span><br><span class="line">    <span class="keyword">if</span> (returnValue == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (isRequestNotModified(webRequest) || hasResponseStatus() || mavContainer.isRequestHandled()) &#123;</span><br><span class="line">            mavContainer.setRequestHandled(<span class="keyword">true</span>);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (StringUtils.hasText(<span class="keyword">this</span>.responseReason)) &#123;</span><br><span class="line">        mavContainer.setRequestHandled(<span class="keyword">true</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    mavContainer.setRequestHandled(<span class="keyword">false</span>);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.returnValueHandlers.handleReturnValue(</span><br><span class="line">                returnValue, getReturnValueType(returnValue), mavContainer, webRequest);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(getReturnValueHandlingErrorMessage(<span class="string">"Error handling return value"</span>, returnValue), ex);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个方法里可以看到，如果返回参数为null且已经响应response，或者mavContainer属性responseReason不为空，则设置mavContainer属性requestHandled为true，可见，如果属性requestHandled为true，adpater就不会生成 ModelAndView。</p>
<p>执行invokeForRequest方法得到返回结果后，会调用<code>returnValueHandlers</code>对结果进行处理，这个处理可能是添加模型数据，又或者是直接写出数据等等。</p>
<p>接下来看invokeForRequest方法吧</p>
<p><code>InvocableHandlerMethod.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Invoke the method after resolving its argument values in the context of the given request.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Argument values are commonly resolved through &#123;<span class="doctag">@link</span> HandlerMethodArgumentResolver&#125;s.</span></span><br><span class="line"><span class="comment"> * The &#123;<span class="doctag">@code</span> providedArgs&#125; parameter however may supply argument values to be used directly,</span></span><br><span class="line"><span class="comment"> * i.e. without argument resolution. Examples of provided argument values include a</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> WebDataBinder&#125;, a &#123;<span class="doctag">@link</span> SessionStatus&#125;, or a thrown exception instance.</span></span><br><span class="line"><span class="comment"> * Provided argument values are checked before argument resolvers.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request the current request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> mavContainer the ModelAndViewContainer for this request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> providedArgs "given" arguments matched by type, not resolved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the raw value returned by the invoked method</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@exception</span> Exception raised if no suitable argument resolver can be found,</span></span><br><span class="line"><span class="comment"> * or if the method raised an exception</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">invokeForRequest</span><span class="params">(NativeWebRequest request, ModelAndViewContainer mavContainer,</span></span></span><br><span class="line"><span class="function"><span class="params">        Object... providedArgs)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);</span><br><span class="line">    <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder(<span class="string">"Invoking ["</span>);</span><br><span class="line">        sb.append(getBeanType().getSimpleName()).append(<span class="string">"."</span>);</span><br><span class="line">        sb.append(getMethod().getName()).append(<span class="string">"] method with arguments "</span>);</span><br><span class="line">        sb.append(Arrays.asList(args));</span><br><span class="line">        logger.trace(sb.toString());</span><br><span class="line">    &#125;</span><br><span class="line">    Object returnValue = doInvoke(args);</span><br><span class="line">    <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">        logger.trace(<span class="string">"Method ["</span> + getMethod().getName() + <span class="string">"] returned ["</span> + returnValue + <span class="string">"]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> returnValue;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Get the method argument values for the current request.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> Object[] getMethodArgumentValues(NativeWebRequest request, ModelAndViewContainer mavContainer,</span><br><span class="line">        Object... providedArgs) <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    MethodParameter[] parameters = getMethodParameters();</span><br><span class="line">    Object[] args = <span class="keyword">new</span> Object[parameters.length];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; parameters.length; i++) &#123;</span><br><span class="line">        MethodParameter parameter = parameters[i];</span><br><span class="line">        parameter.initParameterNameDiscovery(<span class="keyword">this</span>.parameterNameDiscoverer);</span><br><span class="line">        GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());</span><br><span class="line">        args[i] = resolveProvidedArgument(parameter, providedArgs);</span><br><span class="line">        <span class="keyword">if</span> (args[i] != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.argumentResolvers.supportsParameter(parameter)) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                args[i] = <span class="keyword">this</span>.argumentResolvers.resolveArgument(</span><br><span class="line">                        parameter, mavContainer, request, <span class="keyword">this</span>.dataBinderFactory);</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">                <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                    logger.debug(getArgumentResolutionErrorMessage(<span class="string">"Error resolving argument"</span>, i), ex);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">throw</span> ex;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (args[i] == <span class="keyword">null</span>) &#123;</span><br><span class="line">            String msg = getArgumentResolutionErrorMessage(<span class="string">"No suitable resolver for argument"</span>, i);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(msg);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> args;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Invoke the handler method with the given argument values.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">doInvoke</span><span class="params">(Object... args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ReflectionUtils.makeAccessible(getBridgedMethod());</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getBridgedMethod().invoke(getBean(), args);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (IllegalArgumentException ex) &#123;</span><br><span class="line">        assertTargetBean(getBridgedMethod(), getBean(), args);</span><br><span class="line">        String message = (ex.getMessage() != <span class="keyword">null</span> ? ex.getMessage() : <span class="string">"Illegal argument"</span>);</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(getInvocationErrorMessage(message, args), ex);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (InvocationTargetException ex) &#123;</span><br><span class="line">        <span class="comment">// Unwrap for HandlerExceptionResolvers ...</span></span><br><span class="line">        Throwable targetException = ex.getTargetException();</span><br><span class="line">        <span class="keyword">if</span> (targetException <span class="keyword">instanceof</span> RuntimeException) &#123;</span><br><span class="line">            <span class="keyword">throw</span> (RuntimeException) targetException;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (targetException <span class="keyword">instanceof</span> Error) &#123;</span><br><span class="line">            <span class="keyword">throw</span> (Error) targetException;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (targetException <span class="keyword">instanceof</span> Exception) &#123;</span><br><span class="line">            <span class="keyword">throw</span> (Exception) targetException;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            String msg = getInvocationErrorMessage(<span class="string">"Failed to invoke controller method"</span>, args);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(msg, targetException);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>操作相当简单， 先通过<code>parameterNameDiscoverer</code>获取方法的入参名，再通过<code>argumentResolvers</code>获取入参，设置方法为可访问方法，反射调用方法，返回结果。</p>
<h4 id="4-6-9-小结"><a href="#4-6-9-小结" class="headerlink" title="4.6.9 小结"></a>4.6.9 小结</h4><p>RequestMappingHandlerAdapter 之所以比其他adpater复杂，不仅仅是因为它是基于方法的映射，前面的adpater只能根据URI进行映射，而 RequestMappingHandlerAdapter 还同时可以根据Header内容进行规则匹配映射。</p>
<p>从request到方法入参，再到执行，再到返回结果处理，RequestMappingHandlerAdapter 设计了一套精密的结构将这些功能组合到一起，如果让我们自己来写一个基于方法映射的处理器适配器，我觉得难度不是一点点，最起码要耗费比较长的时间才能开发完。</p>
<h3 id="4-7-小结"><a href="#4-7-小结" class="headerlink" title="4.7 小结"></a>4.7 小结</h3><p>HandlerAdapter 它是不用管映射规则的，只用管从 HandlerMapping 中获取到的handler，尽管去执行就好，所以是不是感觉模块划分还算比较合理？要不然映射handler和处理handler放到一起写，那不得愁死了，既要管映射规则，还要管不同的handler不同的处理方式。还要注意一点，handle方法要么返回 ModelAndView 要么返回null，如果返回的是 ModelAndView，那 ViewResolver 必须处理，处理不了就得报错。还有一点，如果你自定义了handler，那么也得自定义一个 HandlerAdapter，要不然对应不上 adapter就会抛出异常。</p>
<p>HandlerAdapter 就先讲到这里了，大家是不是对 ModelAndView 是如何转为视图渲染的更加有兴趣了？也更加有信心了？</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-3/" title="SpringMVC 解毒3">http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-3/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-2/" rel="next" title="SpringMVC 解毒2">
                <i class="fa fa-chevron-left"></i> SpringMVC 解毒2
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-4/" rel="prev" title="SpringMVC 解毒4">
                SpringMVC 解毒4 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-HandlerAdapter"><span class="nav-number">1.</span> <span class="nav-text">4 HandlerAdapter</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-HandlerAdapter-接口"><span class="nav-number">1.1.</span> <span class="nav-text">4.1 HandlerAdapter 接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-SimpleServletHandlerAdapter-分析"><span class="nav-number">1.2.</span> <span class="nav-text">4.2 SimpleServletHandlerAdapter 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-HttpRequestHandlerAdapter-分析"><span class="nav-number">1.3.</span> <span class="nav-text">4.3 HttpRequestHandlerAdapter 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-SimpleControllerHandlerAdapter-分析"><span class="nav-number">1.4.</span> <span class="nav-text">4.4 SimpleControllerHandlerAdapter 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-AbstractHandlerMethodAdapter-分析"><span class="nav-number">1.5.</span> <span class="nav-text">4.5 AbstractHandlerMethodAdapter 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-6-RequestMappingHandlerAdapter-分析"><span class="nav-number">1.6.</span> <span class="nav-text">4.6 RequestMappingHandlerAdapter 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-1-HandlerMethodArgumentResolver-分析"><span class="nav-number">1.6.1.</span> <span class="nav-text">4.6.1 HandlerMethodArgumentResolver 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-2-HandlerMethodReturnValueHandler-分析"><span class="nav-number">1.6.2.</span> <span class="nav-text">4.6.2 HandlerMethodReturnValueHandler 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-3-HttpMessageConverter-分析"><span class="nav-number">1.6.3.</span> <span class="nav-text">4.6.3 HttpMessageConverter 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-4-ParameterNameDiscoverer-分析"><span class="nav-number">1.6.4.</span> <span class="nav-text">4.6.4 ParameterNameDiscoverer 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-5-ModelAndViewContainer-分析"><span class="nav-number">1.6.5.</span> <span class="nav-text">4.6.5 ModelAndViewContainer 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-6-ServletInvocableHandlerMethod-和-InvocableHandlerMethod-分析"><span class="nav-number">1.6.6.</span> <span class="nav-text">4.6.6 ServletInvocableHandlerMethod 和 InvocableHandlerMethod 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-7-RequestMappingHandlerAdapter-初始化分析"><span class="nav-number">1.6.7.</span> <span class="nav-text">4.6.7 RequestMappingHandlerAdapter 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-8-RequestMappingHandlerAdapter-处理请求分析"><span class="nav-number">1.6.8.</span> <span class="nav-text">4.6.8 RequestMappingHandlerAdapter 处理请求分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-6-9-小结"><span class="nav-number">1.6.9.</span> <span class="nav-text">4.6.9 小结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-7-小结"><span class="nav-number">1.7.</span> <span class="nav-text">4.7 小结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-3/';
          this.page.identifier = '2018/08/12/learn-springmvc-code-3/';
          this.page.title = 'SpringMVC 解毒3';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
